package com.malbbmsomanager.receipt;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;

import com.malbbmsomanager.adapter.DM_BBM_List_Adapters;
import com.malbbmsomanager.print.DM_BBM_Receipt_PrintPreview;
import com.malbbmsomanagerdemo.DM_BBM_InvoiceMenu;
import com.malbbmsomanagerdemo.R;

public class DM_BBM_InvoiceSalesReceipt extends Activity implements
		ActionBar.OnNavigationListener {
	// dminvoiceselectinvoices
	/************ Variables Declerations ***************/
	String CustomerCodeInv, CustomerTaxRegNo, slectedMenuOption, Strusername,
			Strlrepprefix, TransTypePrefix, currentRefNumber, currentSerialKey,
			YearMonthStr, CurrencyCode, ExchangeRate, SO_Ref_Number,
			DeviceModel, receiptRefNoSelected;
	private int mYear, mMonth, mDay, mHour, mMinute;
	int resetCode = 0;
	int delPressed = 0;
	int printPreviewPressed = 0;
	int resetActive = 0;
	static final int DATE_DIALOG_ID_FROM = 0;
	private static final String TAG = null;
	// action bar
	private ActionBar actionBar;
	private DM_BBM_List_Adapters dbHelperCustomer;
	private SQLiteDatabase mydb;
	private String DBNAME = "dminvoicemanagerbbm.db";

	private String FCOMPANYBRANCH_TABLE = "FCompanyBranch";
	// Receipt Tranactiob
	private String FPRECHED_TABLE = "FPRecHed";
	private String FPRECDET_TABLE = "FPRecDet";
	private String FDDBNOTE_TABLE = "fddbnote";
	int ReceiptCount = 0;
	int PreviewReceipt = 0;
	String SaveAlertTitle, SaveAlertDetailMessage, macAddress;

	/************ Define Drawable Resources ***************/
	private SimpleCursorAdapter dataAdapterCusomer;
	LinearLayout dminvoiceselectcus, dminvoiceselectbank,
			dminvoiceheadersection, chequedetailspanel,
			dminvoiceselectchequebank, dminvoiceselectcashbank,
			dminvoiceselectinvoices;
	Button buttonSelectCustomer, buttonSelectPayType, btnbbmcusbank,
			btndatebepresent, buttonbbmchqpbankcode, etcachebankacc,
			btnsavetransaction, etbbmsoreferenceno, btnundotransaction,
			btnselectreceipts, btndeletetransaction, btnprinttransaction;
	EditText myFilterCustomer, etbbmsoPayTypeDes, etbbmcusbank,
			etbbmchqpbankdescription, etcachebankaccdetail, etbbmchequeno,
			etbbmsodate, etbbmsocurrencyno, etbbmsomanualno, etbankcharge,
			etbbmsoCustomer, etreceiptrate, etreceiptamount, etbalamount,
			etbbmreceiptremark, etreceiptallocamount;
	AlertDialog InvoiceHeaderAlert = null;

	BigDecimal RecOriAllocatedAmount = new BigDecimal("0.00");
	BigDecimal RecAllocatedAmount = new BigDecimal("0.00");
	BigDecimal RecBalanceAmount = new BigDecimal("0.00");

	BigDecimal TotalAllocatedAmount = new BigDecimal("0.00");
	BigDecimal defaultAllocatedAmount = new BigDecimal("0.00");

	BigDecimal DefaultPendingBal = new BigDecimal("0.00");

	SimpleDateFormat originalFormat = new SimpleDateFormat("dd MM yyyy");
	SimpleDateFormat targetFormat = new SimpleDateFormat("dd/MM/yyyy");
	Date settingDate;

	/*********** On Click Methods ****************/
	public void btnCusListBack(View view) {
		dminvoiceselectcus.setVisibility(view.GONE);
		dminvoiceselectbank.setVisibility(view.GONE);
		dminvoiceselectinvoices.setVisibility(view.GONE);
		dminvoiceheadersection.setVisibility(view.VISIBLE);
	}

	public DM_BBM_InvoiceSalesReceipt() {
		// Assign current Date and Time Values to Variables
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		mHour = c.get(Calendar.HOUR_OF_DAY);
		mMinute = c.get(Calendar.MINUTE);
	}

	// AddReceiptsDetails

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_bbm_invoice_sales_receipt);

		// LinearLayout Parent View Controllers
		dminvoiceheadersection = (LinearLayout) findViewById(R.id.dminvoiceheadersection);
		dminvoiceselectcus = (LinearLayout) findViewById(R.id.dminvoiceselectcus);
		dminvoiceselectbank = (LinearLayout) findViewById(R.id.dminvoiceselectbank);
		chequedetailspanel = (LinearLayout) findViewById(R.id.chequedetailspanel);
		dminvoiceselectchequebank = (LinearLayout) findViewById(R.id.dminvoiceselectchequebank);
		dminvoiceselectcashbank = (LinearLayout) findViewById(R.id.dminvoiceselectcashbank);
		dminvoiceselectinvoices = (LinearLayout) findViewById(R.id.dminvoiceselectinvoices);

		buttonSelectCustomer = (Button) findViewById(R.id.buttonSelectCustomer);
		buttonSelectPayType = (Button) findViewById(R.id.buttonSelectPayType);
		btnbbmcusbank = (Button) findViewById(R.id.btnbbmcusbank);
		btndatebepresent = (Button) findViewById(R.id.btndatebepresent);
		buttonbbmchqpbankcode = (Button) findViewById(R.id.buttonbbmchqpbankcode);
		etcachebankacc = (Button) findViewById(R.id.etcachebankacc);
		/************** Save Invoice Action **************/
		btnsavetransaction = (Button) findViewById(R.id.btnsavetransaction);
		/************** Undo Invoice Action **************/
		btnundotransaction = (Button) findViewById(R.id.btnundotransaction);
		/************** List Invoice Action **************/
		btnselectreceipts = (Button) findViewById(R.id.btnselectreceipts);

		btndeletetransaction = (Button) findViewById(R.id.btndeletetransaction);
		btnprinttransaction = (Button) findViewById(R.id.btnprinttransaction);

		myFilterCustomer = (EditText) findViewById(R.id.dminvfiltercustomer);
		etbbmsoPayTypeDes = (EditText) findViewById(R.id.etbbmsoPayTypeDes);
		etbbmcusbank = (EditText) findViewById(R.id.etbbmcusbank);
		etbbmchqpbankdescription = (EditText) findViewById(R.id.etbbmchqpbankdescription);
		etcachebankaccdetail = (EditText) findViewById(R.id.etcachebankaccdetail);
		etbbmchequeno = (EditText) findViewById(R.id.etbbmchequeno);
		etbbmsoreferenceno = (Button) findViewById(R.id.etbbmsoreferenceno);
		etbbmsodate = (EditText) findViewById(R.id.etbbmsodate);
		etbbmsocurrencyno = (EditText) findViewById(R.id.etbbmsocurrencyno);
		etbbmsomanualno = (EditText) findViewById(R.id.etbbmsomanualno);
		etbankcharge = (EditText) findViewById(R.id.etbankcharge);
		etbbmsoCustomer = (EditText) findViewById(R.id.etbbmsoCustomer);
		etreceiptrate = (EditText) findViewById(R.id.etreceiptrate);
		etreceiptamount = (EditText) findViewById(R.id.etreceiptamount);
		etreceiptallocamount = (EditText) findViewById(R.id.etreceiptallocamount);
		etbalamount = (EditText) findViewById(R.id.etbalamount);
		etbbmreceiptremark = (EditText) findViewById(R.id.etbbmreceiptremark);

		etreceiptamount.addTextChangedListener(calculateBalanceAmountReceived);
		etreceiptallocamount
				.addTextChangedListener(calculateReceiptAmountReceived);

		actionBar = getActionBar();
		// Hide the action bar title
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(false);

		dbHelperCustomer = new DM_BBM_List_Adapters(this);
		dbHelperCustomer.open();

		DeviceModel = android.os.Build.MODEL;

		// Set The Device Mac Address
		WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		WifiInfo wInfo = wifiManager.getConnectionInfo();
		macAddress = wInfo.getMacAddress();
		/************* Display Data *************/
		getLoadCustommers();
		getLoadBanks();
		displayDefaultInfo();
		getLoadChqPresentBank();
		getLoadCashBank();
		getCurrentUser();
		getCompanySettings();
		getCurrentYearMonth();
		getDefCurrencyCode();
		getCurrentRefNumber();
		checkSalesReceiptSaved();
		displayCurrentReceipt();
		displayReceiptSummary();
		displayReceiptsList();

		etbbmsoreferenceno.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				dminvoiceselectcus.setVisibility(view.GONE);
				dminvoiceheadersection.setVisibility(view.GONE);
				dminvoiceselectbank.setVisibility(view.GONE);
				dminvoiceselectcashbank.setVisibility(view.GONE);
				dminvoiceselectchequebank.setVisibility(view.GONE);
				dminvoiceselectinvoices.setVisibility(view.VISIBLE);
				delPressed = 202;
				printPreviewPressed = 202;
			}
		});

		buttonSelectCustomer.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				dminvoiceselectcus.setVisibility(view.VISIBLE);
				dminvoiceheadersection.setVisibility(view.GONE);
				dminvoiceselectbank.setVisibility(view.GONE);
				dminvoiceselectcashbank.setVisibility(view.GONE);
				dminvoiceselectchequebank.setVisibility(view.GONE);
				dminvoiceselectinvoices.setVisibility(view.GONE);
			}

		});

		btnbbmcusbank.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				dminvoiceselectbank.setVisibility(view.VISIBLE);
				dminvoiceselectcus.setVisibility(view.GONE);
				dminvoiceheadersection.setVisibility(view.GONE);
				dminvoiceselectcashbank.setVisibility(view.GONE);
				dminvoiceselectchequebank.setVisibility(view.GONE);
				dminvoiceselectinvoices.setVisibility(view.GONE);
			}

		});

		buttonbbmchqpbankcode.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				dminvoiceselectbank.setVisibility(view.GONE);
				dminvoiceselectcus.setVisibility(view.GONE);
				dminvoiceheadersection.setVisibility(view.GONE);
				dminvoiceselectcashbank.setVisibility(view.GONE);
				dminvoiceselectinvoices.setVisibility(view.GONE);
				dminvoiceselectchequebank.setVisibility(view.VISIBLE);
			}

		});

		etcachebankacc.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				dminvoiceselectbank.setVisibility(view.GONE);
				dminvoiceselectcus.setVisibility(view.GONE);
				dminvoiceheadersection.setVisibility(view.GONE);
				dminvoiceselectcashbank.setVisibility(view.VISIBLE);
				dminvoiceselectchequebank.setVisibility(view.GONE);
				dminvoiceselectinvoices.setVisibility(view.GONE);
			}
		});

		btnselectreceipts.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				dminvoiceselectcus.setVisibility(view.GONE);
				dminvoiceheadersection.setVisibility(view.GONE);
				dminvoiceselectbank.setVisibility(view.GONE);
				dminvoiceselectcashbank.setVisibility(view.GONE);
				dminvoiceselectchequebank.setVisibility(view.GONE);
				dminvoiceselectinvoices.setVisibility(view.VISIBLE);
			}

		});

		btndatebepresent.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// Show the DatePickerDialog
				showDialog(DATE_DIALOG_ID_FROM);
			}
		});

		buttonSelectPayType.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(final View view) {
				// TODO Auto-generated method stub
				PopupMenu popup = new PopupMenu(
						DM_BBM_InvoiceSalesReceipt.this, buttonSelectPayType);
				popup.getMenuInflater().inflate(R.menu.dm_pay_options,
						popup.getMenu());

				popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
					@Override
					public boolean onMenuItemClick(MenuItem item) {
						// TODO Auto-generated method stub
						long FlightOption = item.getItemId();
						slectedMenuOption = item.getTitle().toString();

						String TAG = null;
						Log.v(TAG, "FlightOption :" + slectedMenuOption);

						String[] separated = slectedMenuOption.split("-");
						String PayCode = separated[0]; // this will contain
														// "Fruit"
						String PayCodeDes = separated[1]; // this will contain
															// " they taste good"

						buttonSelectPayType.setText(PayCode);
						etbbmsoPayTypeDes.setText(PayCodeDes);

						if (PayCode.trim().equals("CA")) {
							chequedetailspanel.setVisibility(view.GONE);
							etcachebankacc.setEnabled(true);
							etbankcharge.setEnabled(false);
							etbbmchequeno.setText("");
							btndatebepresent.setText("");
							btnbbmcusbank.setText("");
							etbbmcusbank.setText("");
							buttonbbmchqpbankcode.setText("");
							etbbmchqpbankdescription.setText("");
						} else if (PayCode.trim().equals("CH")) {
							chequedetailspanel.setVisibility(view.VISIBLE);
							etcachebankacc.setEnabled(false);
							etbankcharge.setEnabled(true);
							etcachebankacc.setText("");
							etcachebankaccdetail.setText("");
						}

						return false;
					}
				});
				popup.show();
			}

		});

		// Save Action Button
		btnsavetransaction.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				String PendingBal = etbalamount.getText().toString();
				BigDecimal PendingBalValue = new BigDecimal(PendingBal
						.replaceAll("[,]", ""));
				int resCom;
				resCom = PendingBalValue.compareTo(defaultAllocatedAmount);

				if (resCom == -1) {
					Log.e("TAG", "VALUE 111:" + PendingBal);
					AlertDialog.Builder builderSingle = new AlertDialog.Builder(
							DM_BBM_InvoiceSalesReceipt.this);
					builderSingle.setTitle("Invalid Allocation");
					builderSingle
							.setMessage("Do You Want To Reallocate Receipt Amounts ?");
					builderSingle.setNegativeButton("No",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									String AdditionalAmount = etbalamount
											.getText().toString()
											.replaceAll("-", "");
									String AdjustValue = etreceiptamount
											.getText().toString()
											.replaceAll("-", "");
									BigDecimal AdditionalValAmount = new BigDecimal(
											AdditionalAmount.replaceAll("[,]",
													""));
									BigDecimal AdjustValAmount = new BigDecimal(
											AdjustValue.replaceAll("[,]", ""));
									BigDecimal PrintNewValue = AdditionalValAmount
											.add(AdjustValAmount);
									etreceiptamount.setText("" + PrintNewValue);
									dialog.dismiss();
								}
							});

					builderSingle.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									mydb = openOrCreateDatabase(DBNAME,
											Context.MODE_PRIVATE, null);
									String SelectedRefNo = etbbmsoreferenceno
											.getText().toString();
									try {
										mydb.delete(FPRECDET_TABLE, "RefNo ='"
												+ SelectedRefNo + "'", null);
									} catch (Exception e) {

									}
									/*
									 * etreceiptallocamount.setText("0.00");
									 * etreceiptamount.setText("0.00");
									 * etbalamount.setText("0.00");
									 */
									resetActive = 202;
									DisplayOutStandingReceipts();
									dialog.dismiss();
								}
							});

					AlertDialog alertDialog = builderSingle.create();
					// show alert
					alertDialog.show();

				} else {
					updateReceiptHeaderDetails();
					checkCustomer();
				}
			}
		});

		// Undo Action Button
		btnundotransaction.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (PreviewReceipt == 202) {
					AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
							DM_BBM_InvoiceSalesReceipt.this);
					alertDialogBuilder.setTitle("EXIT PREVIEW");
					alertDialogBuilder.setMessage("Exit From Receipt Preview");
					// set positive button: Yes message
					alertDialogBuilder.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									BackAction();
								}
							});
					// set negative button: No message
					alertDialogBuilder.setNegativeButton("No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {

									dialog.cancel();
								}
							});
					AlertDialog alertDialog = alertDialogBuilder.create();
					// show alert
					alertDialog.show();
				} else {
					checkCurrentInvoiceState();
				}

			}
		});

		// Delete Receipt
		btndeletetransaction.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				if (delPressed == 0) {
					AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
							DM_BBM_InvoiceSalesReceipt.this);
					alertDialogBuilder.setTitle("SELECT INVOICE");
					alertDialogBuilder
							.setMessage("Please Select Sales Order From Lisr.....");
					// set positive button: Yes message
					alertDialogBuilder.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});

					AlertDialog alertDialog = alertDialogBuilder.create();
					// show alert
					alertDialog.show();

				} else if (delPressed == 202) {
					checkReceiptUploaded();
					// receiptDeleteAlertDialog();
				}

			}
		});

		// Print Button Action
		btnprinttransaction.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				if (printPreviewPressed == 0) {

					AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
							DM_BBM_InvoiceSalesReceipt.this);
					alertDialogBuilder.setTitle("SELECT INVOICE");
					alertDialogBuilder
							.setMessage("Please Select Sales Order From Lisr.....");
					// set positive button: Yes message
					alertDialogBuilder.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});

					AlertDialog alertDialog = alertDialogBuilder.create();
					// show alert
					alertDialog.show();
				}

				else if (printPreviewPressed == 202) {
					Intent myIntent = new Intent(getBaseContext(),
							DM_BBM_Receipt_PrintPreview.class);
					String ReceiptReference = etbbmsoreferenceno.getText()
							.toString();
					myIntent.putExtra("TAGID", ReceiptReference);
					myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
							| Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(myIntent);
					finish();
					return;
				}
			}
		});

	}

	protected void checkReceiptUploaded() {
		// TODO Auto-generated method stub
		Cursor checkPendingReceiptUploads = null;
		try {
			checkPendingReceiptUploads = mydb.query(FPRECHED_TABLE, null,
					"SyncState ='1' AND ActiveState !='1'", null, null, null,
					null);
		} catch (Exception e) {
		}

		if (checkPendingReceiptUploads != null) {
			if (checkPendingReceiptUploads.getCount() > 0) {
				showAlertDialog(
						DM_BBM_InvoiceSalesReceipt.this,
						"INVALID RECEIPT",
						"Selected Receipt Already Uploaded. Permission Denied To Delete...",
						false);
			} else {
				receiptDeleteAlertDialog();
			}
		}
	}

	protected void receiptDeleteAlertDialog() {
		// TODO Auto-generated method stub
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				DM_BBM_InvoiceSalesReceipt.this);
		alertDialogBuilder.setTitle("DELETE RECEIPT");
		alertDialogBuilder.setMessage("Delete Current Receipt");
		// set positive button: Yes message
		alertDialogBuilder.setPositiveButton("Yes",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						deleteReceiptsDetails();
						deleteSuccess();
					}

					private void deleteSuccess() {
						// TODO Auto-generated method stub
						AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
								DM_BBM_InvoiceSalesReceipt.this);
						alertDialogBuilder.setTitle("DELETE SUCCESS");
						alertDialogBuilder
								.setMessage("Selected Receipt Deleted Success..");
						// set positive button: Yes message
						alertDialogBuilder.setPositiveButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										BackAction();
									}
								});
						AlertDialog alertDialog = alertDialogBuilder.create();
						// show alert
						alertDialog.show();
					}

					private void deleteReceiptsDetails() {
						// TODO Auto-generated method stub
						// FPRecDet,FPRecHed,fddbnote
						// FPRECHED_TABLE,FPRECDET_TABLE,FDDBNOTE_TABLE
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						try {
							mydb.delete(FPRECHED_TABLE, "RefNo ='"
									+ receiptRefNoSelected + "'", null);
						} catch (Exception e) {

						}

						// Get Receipt Detail
						Cursor RecDetailsupdate = null;
						try {
							String queryListInvdel = "SELECT RefNo1,Amt FROM FPRecDet WHERE RefNo ='"
									+ receiptRefNoSelected + "'";
							RecDetailsupdate = mydb.rawQuery(queryListInvdel,
									null);
						} catch (Exception e) {
						}
						if (RecDetailsupdate != null) {
							if (RecDetailsupdate.getCount() > 0) {
								while (RecDetailsupdate.moveToNext()) {

									String receiptNo = RecDetailsupdate
											.getString(0);// Receipt No
									String receiptAllocAmt = RecDetailsupdate
											.getString(1);// Receipt No

									Log.v(TAG, "receiptAllocAmt :"
											+ receiptAllocAmt);
									// Update FddbNote

									Cursor receiptDetails = null;
									try {
										String queryreceiptDetails = "SELECT RefNo,Totbal FROM fddbnote WHERE RefNo ='"
												+ receiptNo + "'";
										receiptDetails = mydb.rawQuery(
												queryreceiptDetails, null);
									} catch (Exception e) {
									}

									if (receiptDetails != null) {
										if (receiptDetails.getCount() > 0) {
											while (receiptDetails.moveToNext()) {
												String RefNo = receiptDetails
														.getString(0);// Receipt
																		// No
												String totBalRec = receiptDetails
														.getString(1);// Receipt
																		// No

												BigDecimal receiptAllocAmtVal = new BigDecimal(
														receiptAllocAmt
																.replaceAll(
																		"[,]",
																		""));
												BigDecimal totBalRecVal = new BigDecimal(
														totBalRec.replaceAll(
																"[,]", ""));
												BigDecimal adjustTotBal = receiptAllocAmtVal
														.add(totBalRecVal);

												ContentValues update_Receipt_header = new ContentValues();
												update_Receipt_header.put(
														"Totbal", ""
																+ adjustTotBal);

												mydb.update(
														FDDBNOTE_TABLE,
														update_Receipt_header,
														"RefNo = '"
																+ RefNo.trim()
																+ "'", null);
											}
										}
									}

								}
							}
						}

					}
				});
		// set negative button: No message
		alertDialogBuilder.setNegativeButton("No/Exit",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						BackAction();
						dialog.cancel();
					}
				});

		alertDialogBuilder.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						dialog.cancel();
					}
				});
		AlertDialog alertDialog = alertDialogBuilder.create();
		// show alert
		alertDialog.show();
	}

	private void displayReceiptsList() {
		// TODO Auto-generated method stub
		ListView InvoicesList = (ListView) findViewById(R.id.listviewInvoices);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "colinvoice_1", "colinvoice_2" };
		int[] totrdes = new int[] { R.id.receiptdisplaynumber,
				R.id.receiptdisplaysumary };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowtypedes = null;

		try {
			String queryListInv = "SELECT RefNo, TxnDate FROM FPRecHed WHERE ActiveState ='0'";
			allrowtypedes = mydb.rawQuery(queryListInv, null);
		} catch (Exception e) {
		}
		if (allrowtypedes != null) {
			if (allrowtypedes.getCount() > 0) {
				while (allrowtypedes.moveToNext()) {
					String ReceiptRefNo = allrowtypedes.getString(0);
					String ReceiptTxnDate = allrowtypedes.getString(1);

					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("colinvoice_1", ReceiptTxnDate + ":"
							+ ReceiptRefNo);
					maptrdes.put("colinvoice_2", ReceiptRefNo);

					fillMapstrdes.add(maptrdes);
				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_bbm_receipts_list_raw,
						fromtrdes, totrdes);
				InvoicesList.setAdapter(adaptertrdes);
			}
		}
		allrowtypedes.close();
		mydb.close();
	}

	// Undo Action Button function
	protected void checkCurrentInvoiceState() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		String currentRefNo = etbbmsoreferenceno.getText().toString();
		Cursor checkReceiptState = null;
		try {
			String queryChkSalesOrder = "SELECT ActiveState FROM FPRecHed WHERE RefNo = '"
					+ currentRefNo + "'";
			checkReceiptState = mydb.rawQuery(queryChkSalesOrder, null);

		} catch (Exception e) {
		}
		if (checkReceiptState != null) {
			if (checkReceiptState.getCount() > 0) {
				while (checkReceiptState.moveToNext()) {
					String CurrentState = checkReceiptState.getString(0);
					if (CurrentState.equals("1")) {
						AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
								DM_BBM_InvoiceSalesReceipt.this);
						alertDialogBuilder.setTitle("UNDO RECEIPT");
						alertDialogBuilder
								.setMessage("Undo Current Receipt Details");
						// set positive button: Yes message
						alertDialogBuilder.setPositiveButton("Yes",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										undoActionActivate();
									}
								});
						// set negative button: No message
						alertDialogBuilder.setNegativeButton("No",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {

										dialog.cancel();
									}
								});
						// set neutral button: Exit the app message
						alertDialogBuilder.setNeutralButton("Cancel",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {

										dialog.cancel();
									}
								});

						AlertDialog alertDialog = alertDialogBuilder.create();
						// show alert
						alertDialog.show();
					}
				}
			}
		}
	}

	protected void undoActionActivate() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		String SelectedRefNo = etbbmsoreferenceno.getText().toString();
		try {
			mydb.delete(FPRECDET_TABLE, "RefNo ='" + SelectedRefNo + "'", null);
		} catch (Exception e) {

		}

		try {
			ContentValues add_Receipt_header = new ContentValues();
			add_Receipt_header.put("RefNo", SelectedRefNo);
			add_Receipt_header.put("ManuRef", "");
			add_Receipt_header.put("SaleRefNo", "");
			add_Receipt_header.put("RepCode", Strusername);
			add_Receipt_header.put("TxnType", "40");
			add_Receipt_header.put("Chqno", "");
			add_Receipt_header.put("ChqDate", "");
			add_Receipt_header.put("TxnDate", getDeviceTaxnDate().toString());
			add_Receipt_header.put("CurCode", CurrencyCode);
			add_Receipt_header.put("CurRate1", "0.000000");
			add_Receipt_header.put("DebCode", "");
			add_Receipt_header.put("TotalAmt", "0.00");
			add_Receipt_header.put("BTotalAmt", "0.00");
			add_Receipt_header.put("BankCur", "");
			add_Receipt_header.put("BankRate", "1.000000");
			add_Receipt_header.put("BankAmt", "0.00");
			add_Receipt_header.put("BankCharge", "0.00");
			add_Receipt_header.put("BBankChg", "0.00");
			add_Receipt_header.put("GnLsCal", "Y");
			add_Receipt_header.put("DbAcc", "");
			add_Receipt_header.put("PayType", "");
			add_Receipt_header.put("PrtCopy", "1");
			add_Receipt_header.put("GlPost", "");
			add_Receipt_header.put("Remarks", "");
			add_Receipt_header.put("CardSlipNo", "");
			add_Receipt_header.put("ExpDate", "");
			add_Receipt_header.put("CrdTypCode", "");
			add_Receipt_header.put("CCBankAmt", "0.00");
			add_Receipt_header.put("GlBatch", "");
			add_Receipt_header.put("AddUser", Strusername);
			add_Receipt_header.put("AddMach", macAddress);
			add_Receipt_header.put("AddDate", "");
			add_Receipt_header.put("CurRate", "1.000000");
			add_Receipt_header.put("customer_name", "");
			add_Receipt_header.put("payTypeDes", "");
			add_Receipt_header.put("CACHAcNo", "");
			add_Receipt_header.put("CACHAcBank", "");
			add_Receipt_header.put("CusBankCode", "");
			add_Receipt_header.put("CusBankName", "");
			add_Receipt_header.put("ActiveState", "1");
			add_Receipt_header.put("SyncState", "0");
			add_Receipt_header.put("AllocatedOriAmount", "0.00");
			add_Receipt_header.put("AllocatedAmount", "0.00");
			mydb.update(FPRECHED_TABLE, add_Receipt_header, "RefNo = '"
					+ SelectedRefNo + "'", null);

		} catch (Exception e) {

		}
		mydb.close();
		if (resetCode == 100) {
			resetSuccess();
		} else {
			UndoSuccess();
		}

	}

	private void resetSuccess() {
		// TODO Auto-generated method stub
		final AlertDialog alertDialog = new AlertDialog.Builder(
				DM_BBM_InvoiceSalesReceipt.this).create();
		// Setting Dialog Title
		alertDialog.setTitle("RECEIPT RESET");
		// Setting Dialog Message
		alertDialog.setMessage("Reset Current Receipt Success..");
		// Setting Icon to Dialog
		alertDialog.setIcon(R.drawable.warning);
		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				reloadViews();
				alertDialog.dismiss();
			}
		});
		// Showing Alert Message
		alertDialog.show();
		alertDialog.setCanceledOnTouchOutside(false);
		return;
	}

	private void UndoSuccess() {
		// TODO Auto-generated method stub
		final AlertDialog alertDialog = new AlertDialog.Builder(
				DM_BBM_InvoiceSalesReceipt.this).create();
		// Setting Dialog Title
		alertDialog.setTitle("RECEIPT UPDATED");
		// Setting Dialog Message
		alertDialog.setMessage("Undo Current Receipt Success..");
		// Setting Icon to Dialog
		alertDialog.setIcon(R.drawable.warning);
		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				reloadViews();
				alertDialog.dismiss();
			}
		});
		// Showing Alert Message
		alertDialog.show();
		alertDialog.setCanceledOnTouchOutside(false);
		return;
	}

	protected void reloadViews() {
		// TODO Auto-generated method stub
		Intent myIntent = new Intent(getBaseContext(),
				DM_BBM_InvoiceSalesReceipt.class);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}

	private void displayReceiptSummary() {
		// TODO Auto-generated method stub
		// if(buttonSelectCustomer.length()!=0){
		CustomerCodeInv = buttonSelectCustomer.getText().toString();
		DisplayOutStandingReceipts();
		Log.v(TAG, "******displayReceiptSummary: |" + CustomerCodeInv + "|");
		// }
	}

	private void displayCurrentReceipt() {
		// TODO Auto-generated method stub
		Log.v(TAG, "******displayCurrentReceipt: " + SO_Ref_Number);
		Cursor chkCurrentSalesOrder = null;
		try {
			String queryChkSalesOrder = "SELECT * FROM FPRecHed WHERE RefNo = '"
					+ SO_Ref_Number + "' AND  ActiveState ='1'";
			chkCurrentSalesOrder = mydb.rawQuery(queryChkSalesOrder, null);

		} catch (Exception e) {
		}
		if (chkCurrentSalesOrder != null) {
			if (chkCurrentSalesOrder.getCount() > 0) {
				while (chkCurrentSalesOrder.moveToNext()) {
					Log.v(TAG, "******Display Current Receipt Summary 1");
					String RefNo = chkCurrentSalesOrder.getString(1);
					String TxnDate = chkCurrentSalesOrder.getString(8);
					String CurCode = chkCurrentSalesOrder.getString(9);
					String ManuRef = chkCurrentSalesOrder.getString(2);
					String DebCode = chkCurrentSalesOrder.getString(11);
					String customer_name = chkCurrentSalesOrder.getString(34);
					String PayType = chkCurrentSalesOrder.getString(21);
					String payTypeDes = chkCurrentSalesOrder.getString(35);
					String Chqno = chkCurrentSalesOrder.getString(6);
					String ChqDate = chkCurrentSalesOrder.getString(7);
					String CusBankCode = chkCurrentSalesOrder.getString(38);
					String CusBankName = chkCurrentSalesOrder.getString(39);
					String CACHAcNo = chkCurrentSalesOrder.getString(36);
					String CACHAcBank = chkCurrentSalesOrder.getString(37);
					String BankRate = chkCurrentSalesOrder.getString(15);
					String TotalAmt = chkCurrentSalesOrder.getString(12);
					String BTotalAmt = chkCurrentSalesOrder.getString(13);
					String BankCharge = chkCurrentSalesOrder.getString(17);
					String Remarks = chkCurrentSalesOrder.getString(24);
					String ActiveState = chkCurrentSalesOrder.getString(40);
					String OriginalAllocateAmount = chkCurrentSalesOrder
							.getString(42);
					String ReceiptsAllocateAmount = chkCurrentSalesOrder
							.getString(43);

					Log.v(TAG, "******Display Current Receipt Summary 2  : |"
							+ PayType + "|" + ActiveState);
					etbbmsoreferenceno.setText(RefNo.trim());
					etbbmsodate.setText(getDeviceTaxnDate().toString());
					etbbmsocurrencyno.setText(CurCode);
					etbbmsomanualno.setText(ManuRef);
					buttonSelectCustomer.setText(DebCode);
					etbbmsoCustomer.setText(customer_name);
					buttonSelectPayType.setText(PayType);
					etbbmsoPayTypeDes.setText(payTypeDes);

					etbbmchequeno.setText(Chqno);
					btndatebepresent.setText(ChqDate);
					btnbbmcusbank.setText(CusBankCode);
					etbbmcusbank.setText(CusBankName);
					if (PayType.trim().equals("CH")) {
						chequedetailspanel.setVisibility(LinearLayout.VISIBLE);
						buttonbbmchqpbankcode.setText(CACHAcNo);
						etbbmchqpbankdescription.setText(CACHAcBank);
						Log.v(TAG, "******PRINT CH 1: " + CACHAcNo);
						Log.v(TAG, "******PRINT CH 2: " + CACHAcBank);
					} else if (PayType.trim().equals("CA")) {
						etcachebankacc.setText(CACHAcNo);
						etcachebankaccdetail.setText(CACHAcBank);
						Log.v(TAG, "******PRINT CA 1: " + CACHAcNo);
						Log.v(TAG, "******PRINT CA 2: " + CACHAcBank);
					} else {
						buttonSelectPayType.setText("CA");
						etbbmsoPayTypeDes.setText("CASH");
					}

					etreceiptrate.setText(BankRate);
					etreceiptamount.setText(OriginalAllocateAmount);

					// etbalamount.setText(ReceiptsAllocateAmount);
					BigDecimal PRecOriAllocatedAmount = new BigDecimal(
							OriginalAllocateAmount.replaceAll("[,]", ""));
					BigDecimal PRecAllocatedAmount = new BigDecimal(
							ReceiptsAllocateAmount.replaceAll("[,]", ""));

					BigDecimal PRecBalanceAmount = PRecOriAllocatedAmount
							.subtract(PRecAllocatedAmount);
					PRecBalanceAmount = PRecBalanceAmount.setScale(2,
							BigDecimal.ROUND_HALF_DOWN);
					etbalamount.setText("" + PRecBalanceAmount);
					// etbalamount.setText(BTotalAmt);
					etbankcharge.setText(BankCharge);
					etbbmreceiptremark.setText(Remarks);

				}
			} else {
				Log.v(TAG, "******FAIL");
			}
		}

		// DisplayReceiptDetails();
	}

	private void DisplayOutStandingReceipts() {

		if (resetActive == 202) {
			CustomerCodeInv = buttonSelectCustomer.getText().toString();
		}
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.dminvoiceitemsdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2", "coldes_3",
				"coldes_4", "coldes_5", "coldes_6", "coldes_7", "coldes_8",
				"coldes_9", "coldes_10", "coldes_11", "coldes_12" };

		int[] totrdes = new int[] { R.id.grid_value_a, R.id.grid_value_b,
				R.id.grid_value_c, R.id.grid_value_d, R.id.grid_value_e,
				R.id.grid_value_f, R.id.grid_value_g, R.id.grid_value_h,
				R.id.grid_value_i, R.id.grid_value_j, R.id.grid_value_k,
				R.id.rawindexvalues };

		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curListReceiptDetails = null;

		try {
			String querySelectDebtor = "SELECT * FROM fddbnote WHERE DebCode = '"
					+ CustomerCodeInv.trim() + "'";
			curListReceiptDetails = mydb.rawQuery(querySelectDebtor, null);
		} catch (Exception e) {
		}

		if (curListReceiptDetails != null) {
			if (curListReceiptDetails.getCount() > 0) {
				while (curListReceiptDetails.moveToNext()) {
					String ReceiptRef = etbbmsoreferenceno.getText().toString();
					String record_0 = curListReceiptDetails.getString(0);// index
					String record_1 = curListReceiptDetails.getString(1);// RefNo
					String record_2 = curListReceiptDetails.getString(2);// TxnDate
					String record_3 = curListReceiptDetails.getString(3);// BAmt
					String record_4 = curListReceiptDetails.getString(4);// DebCode
					String record_5 = curListReceiptDetails.getString(5);// RecordId
					String record_6 = curListReceiptDetails.getString(6);// ManuRef
					String record_7 = curListReceiptDetails.getString(7);// Curcode
					String record_8 = curListReceiptDetails.getString(8);// Amt
					String record_9 = curListReceiptDetails.getString(9);// Totbal
					String record_10 = curListReceiptDetails.getString(10);// Remarks
					String record_11 = curListReceiptDetails.getString(11);// RepCode
					String FPRDrecord_12 = "0.00";
					BigDecimal StrTotalAllocatedAmount = new BigDecimal("0.00");
					// Read Data From FPRecDet Table
					Cursor curFPRecDet = null;
					try {
						String querySelectcurFPRecDet = "SELECT * FROM FPRecDet WHERE RefNo1 = '"
								+ record_1.trim()
								+ "' AND RefNo ='"
								+ ReceiptRef + "'";
						curFPRecDet = mydb.rawQuery(querySelectcurFPRecDet,
								null);
					} catch (Exception e) {
					}
					if (curFPRecDet != null) {
						if (curFPRecDet.getCount() > 0) {
							while (curFPRecDet.moveToNext()) {
								// Allocated Amount gggg
								try {
									FPRDrecord_12 = curFPRecDet.getString(13);// Amt
									StrTotalAllocatedAmount = new BigDecimal(
											FPRDrecord_12.replaceAll("[,]", ""));
									TotalAllocatedAmount = TotalAllocatedAmount
											.add(StrTotalAllocatedAmount);
								} catch (Exception e) {
									Log.v(TAG, "Exception  :" + e);
									TotalAllocatedAmount = new BigDecimal(
											"0.00");
								}

							}
						}
					}

					BigDecimal StrTotalPendingAmount = new BigDecimal(
							record_9.replaceAll("[,]", ""));
					BigDecimal BalanceAmount = StrTotalPendingAmount
							.subtract(StrTotalAllocatedAmount);

					/*
					 * TotalAllocatedAmount = TotalAllocatedAmount
					 * .add(StrTotalAllocatedAmount);
					 */

					String[] record_2Array = record_2.split(" ");
					record_2 = record_2Array[0]; // this will contain Date Part
					String[] record_3Array = record_2.split("/");
					String month = record_3Array[0];
					String day = record_3Array[1];
					String Year = record_3Array[2];

					Log.v(TAG, "record_2 ****** :" + record_2);

					if (month.length() == 1) {
						month = "0" + month;
					} else if (day.length() == 1) {
						day = "0" + day;
					}
					record_2 = day + "/" + month + "/" + Year;
					try {
						settingDate = originalFormat.parse(record_2.replaceAll(
								"[-+/.^:,]", " "));
						record_2 = targetFormat.format(settingDate);
					} catch (ParseException ex) {
						Log.v(TAG, "Exception ****** :" + ex);
						record_2 = getDeviceTaxnDate().toString();
					}

					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", record_1);
					maptrdes.put("coldes_2", record_6);
					maptrdes.put("coldes_3", record_2);
					maptrdes.put("coldes_4", record_7);
					maptrdes.put("coldes_5", record_8);
					maptrdes.put("coldes_6", record_9);
					maptrdes.put("coldes_7", FPRDrecord_12);
					maptrdes.put("coldes_8", "" + BalanceAmount);
					maptrdes.put("coldes_9", "0.00");
					maptrdes.put("coldes_10", record_10);
					maptrdes.put("coldes_11", "");
					maptrdes.put("coldes_12", record_1);
					fillMapstrdes.add(maptrdes);

					// fill in the grid_item layout
					SimpleAdapter adaptertrdes = new SimpleAdapter(this,
							fillMapstrdes, R.layout.dm_bbm_receipt_details_raw,
							fromtrdes, totrdes);
					lvtypedes.setAdapter(adaptertrdes);

					ReceiptCount = ReceiptCount + 1;
				}
			} else {
				HashMap<String, String> maptrdes = new HashMap<String, String>();
				maptrdes.put("coldes_1", "");
				maptrdes.put("coldes_2", "");
				maptrdes.put("coldes_3", "");
				maptrdes.put("coldes_4", "");
				maptrdes.put("coldes_5", "");
				maptrdes.put("coldes_6", "");
				maptrdes.put("coldes_7", "");
				maptrdes.put("coldes_8", "");
				maptrdes.put("coldes_9", "");
				maptrdes.put("coldes_10", "");
				maptrdes.put("coldes_11", "");
				maptrdes.put("coldes_12", "");
				fillMapstrdes.add(maptrdes);

				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_bbm_receipt_details_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		etreceiptallocamount.setText("" + TotalAllocatedAmount);
	}

	private void DisplayReceiptPreviewDetails() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.dminvoiceitemsdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2", "coldes_3",
				"coldes_4", "coldes_5", "coldes_6", "coldes_7", "coldes_8",
				"coldes_9", "coldes_10", "coldes_11", "coldes_12" };

		int[] totrdes = new int[] { R.id.grid_value_a, R.id.grid_value_b,
				R.id.grid_value_c, R.id.grid_value_d, R.id.grid_value_e,
				R.id.grid_value_f, R.id.grid_value_g, R.id.grid_value_h,
				R.id.grid_value_i, R.id.grid_value_j, R.id.grid_value_k,
				R.id.rawindexvalues };

		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curListReceiptDetails = null;

		try {
			String querySelectDebtor = "SELECT * FROM fddbnote WHERE DebCode = '"
					+ CustomerCodeInv.trim() + "'";
			curListReceiptDetails = mydb.rawQuery(querySelectDebtor, null);
		} catch (Exception e) {
		}

		if (curListReceiptDetails != null) {
			if (curListReceiptDetails.getCount() > 0) {
				while (curListReceiptDetails.moveToNext()) {

					String ReceiptRef = etbbmsoreferenceno.getText().toString();
					String record_0 = curListReceiptDetails.getString(0);// index
					String record_1 = curListReceiptDetails.getString(1);// RefNo
					String record_2 = curListReceiptDetails.getString(2);// TxnDate
					String record_3 = curListReceiptDetails.getString(3);// BAmt
					String record_4 = curListReceiptDetails.getString(4);// DebCode
					String record_5 = curListReceiptDetails.getString(5);// RecordId
					String record_6 = curListReceiptDetails.getString(6);// ManuRef
					String record_7 = curListReceiptDetails.getString(7);// Curcode
					String record_8 = curListReceiptDetails.getString(8);// Amt
					String record_9 = curListReceiptDetails.getString(9);// Totbal
					String record_10 = curListReceiptDetails.getString(10);// Remarks
					String record_11 = curListReceiptDetails.getString(11);// RepCode
					String FPRDrecord_12 = "0.00";
					BigDecimal StrTotalAllocatedAmount = new BigDecimal("0.00");
					// Read Data From FPRecDet Table
					Cursor curFPRecDet = null;
					try {
						String querySelectcurFPRecDet = "SELECT * FROM FPRecDet WHERE RefNo1 = '"
								+ record_1.trim()
								+ "' AND RefNo ='"
								+ ReceiptRef + "'";
						curFPRecDet = mydb.rawQuery(querySelectcurFPRecDet,
								null);
					} catch (Exception e) {
					}
					if (curFPRecDet != null) {
						if (curFPRecDet.getCount() > 0) {
							while (curFPRecDet.moveToNext()) {
								// Allocated Amount gggg
								try {
									FPRDrecord_12 = curFPRecDet.getString(13);// Amt
									StrTotalAllocatedAmount = new BigDecimal(
											FPRDrecord_12.replaceAll("[,]", ""));
									TotalAllocatedAmount = TotalAllocatedAmount
											.add(StrTotalAllocatedAmount);
								} catch (Exception e) {
									Log.v(TAG, "Exception  :" + e);
									TotalAllocatedAmount = new BigDecimal(
											"0.00");
								}

								String[] record_2Array = record_2.split(" ");
								record_2 = record_2Array[0]; // this will
																// contain Date
																// Part
								String[] record_3Array = record_2.split("/");
								String month = record_3Array[0];
								String day = record_3Array[1];
								String Year = record_3Array[2];

								Log.v(TAG, "record_2 ****** :" + record_2);

								if (month.length() == 1) {
									month = "0" + month;
								} else if (day.length() == 1) {
									day = "0" + day;
								}
								record_2 = day + "/" + month + "/" + Year;
								try {
									settingDate = originalFormat.parse(record_2
											.replaceAll("[-+/.^:,]", " "));
									record_2 = targetFormat.format(settingDate);
								} catch (ParseException ex) {
									Log.v(TAG, "Exception ****** :" + ex);
									record_2 = getDeviceTaxnDate().toString();
								}

								BigDecimal StrTotalPendingAmount = new BigDecimal(
										record_9.replaceAll("[,]", ""));
								BigDecimal BalanceAmount = StrTotalPendingAmount
										.subtract(StrTotalAllocatedAmount);

								HashMap<String, String> maptrdes = new HashMap<String, String>();
								maptrdes.put("coldes_1", record_1);
								maptrdes.put("coldes_2", record_6);
								maptrdes.put("coldes_3", record_2);
								maptrdes.put("coldes_4", record_7);
								maptrdes.put("coldes_5", record_8);
								maptrdes.put("coldes_6", record_9);
								maptrdes.put("coldes_7", FPRDrecord_12);
								maptrdes.put("coldes_8", "" + record_9);
								maptrdes.put("coldes_9", "0.00");
								maptrdes.put("coldes_10", record_10);
								maptrdes.put("coldes_11", "");
								maptrdes.put("coldes_12", record_1);
								fillMapstrdes.add(maptrdes);

								// fill in the grid_item layout
								SimpleAdapter adaptertrdes = new SimpleAdapter(
										this, fillMapstrdes,
										R.layout.dm_bbm_receipt_details_raw,
										fromtrdes, totrdes);
								lvtypedes.setAdapter(adaptertrdes);

							}
						}
					}

					ReceiptCount = ReceiptCount + 1;
				}
			} else {
				HashMap<String, String> maptrdes = new HashMap<String, String>();
				maptrdes.put("coldes_1", "");
				maptrdes.put("coldes_2", "");
				maptrdes.put("coldes_3", "");
				maptrdes.put("coldes_4", "");
				maptrdes.put("coldes_5", "");
				maptrdes.put("coldes_6", "");
				maptrdes.put("coldes_7", "");
				maptrdes.put("coldes_8", "");
				maptrdes.put("coldes_9", "");
				maptrdes.put("coldes_10", "");
				maptrdes.put("coldes_11", "");
				maptrdes.put("coldes_12", "");
				fillMapstrdes.add(maptrdes);

				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_bbm_receipt_details_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		etreceiptallocamount.setText("" + TotalAllocatedAmount);
	}

	private void checkSalesReceiptSaved() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		/*
		 * mydb.execSQL("DROP TABLE IF EXISTS FPRecHed");
		 * mydb.execSQL("DROP TABLE IF EXISTS FPRecDet");
		 * 
		 * mydb.execSQL("create table if not exists " + FPRECHED_TABLE +
		 * "(fpreched_id integer primary key autoincrement,RefNo text not null,ManuRef text not null,SaleRefNo text not null,RepCode text not null,TxnType text not null,Chqno text not null,ChqDate text not null,TxnDate text not null,CurCode text not null,CurRate1 text not null,DebCode text not null,TotalAmt text not null,BTotalAmt text not null,BankCur text not null,BankRate text not null,BankAmt text not null,BankCharge text not null,BBankChg text not null,GnLsCal text not null,DbAcc text not null,PayType text not null,PrtCopy text not null,GlPost text not null,Remarks text not null,CardSlipNo text not null,ExpDate text not null,CrdTypCode text not null,CCBankAmt text not null,GlBatch text not null,AddUser text not null,AddMach text not null,AddDate text not null,CurRate text not null,customer_name text not null,payTypeDes text not null,CACHAcNo text not null,CACHAcBank text not null,CusBankCode text not null,CusBankName text not null,ActiveState text not null,SyncState text not null,AllocatedOriAmount text not null,AllocatedAmount text not null);"
		 * );
		 * 
		 * mydb.execSQL("create table if not exists " + FPRECDET_TABLE +
		 * "(fprecdet_id	integer primary key autoincrement,RefNo text not null,RefNo1 text not null,SaleRefNo text not null,ManuRef text not null,TxnType text not null,TxnDate text not null,DtxnDate text not null,DtxnType text not null,DCurCode text not null,DCurRate text not null,OCurRate text not null,RepCode text not null,Amt text not null,BAmt text not null,GainLosAmt text not null,BnkChgs text not null,BBnkChgs text not null,AloAmt text not null,OvPayAmt text not null,OvPayBal text not null,SyncState text not null);"
		 * );
		 */

		Cursor chkSalesOrder = null;
		try {
			String queryChkSalesOrder = "SELECT * FROM FPRecHed WHERE RefNo = '"
					+ SO_Ref_Number + "'";
			chkSalesOrder = mydb.rawQuery(queryChkSalesOrder, null);

		} catch (Exception e) {
		}

		if (chkSalesOrder != null) {
			if (chkSalesOrder.getCount() > 0) {
				while (chkSalesOrder.moveToNext()) {
					Log.v(TAG, "Receipt Invoice Available");
				}
			} else {
				Log.v(TAG, "Add Current Receipt Details");
				ContentValues add_Receipt_header = new ContentValues();
				add_Receipt_header.put("RefNo", SO_Ref_Number);
				add_Receipt_header.put("ManuRef", "");
				add_Receipt_header.put("SaleRefNo", "");
				add_Receipt_header.put("RepCode", Strusername);
				add_Receipt_header.put("TxnType", "40");
				add_Receipt_header.put("Chqno", "");
				add_Receipt_header.put("ChqDate", "");
				add_Receipt_header.put("TxnDate", getDeviceTaxnDate()
						.toString());
				add_Receipt_header.put("CurCode", CurrencyCode);
				add_Receipt_header.put("CurRate1", "0.000000");
				add_Receipt_header.put("DebCode", "");
				add_Receipt_header.put("TotalAmt", "");
				add_Receipt_header.put("BTotalAmt", "");
				add_Receipt_header.put("BankCur", "");
				add_Receipt_header.put("BankRate", "1.000000");
				add_Receipt_header.put("BankAmt", "");
				add_Receipt_header.put("BankCharge", "");
				add_Receipt_header.put("BBankChg", "");
				add_Receipt_header.put("GnLsCal", "Y");
				add_Receipt_header.put("DbAcc", "");
				add_Receipt_header.put("PayType", "");
				add_Receipt_header.put("PrtCopy", "1");
				add_Receipt_header.put("GlPost", "");
				add_Receipt_header.put("Remarks", "");
				add_Receipt_header.put("CardSlipNo", "");
				add_Receipt_header.put("ExpDate", "");
				add_Receipt_header.put("CrdTypCode", "");
				add_Receipt_header.put("CCBankAmt", "");
				add_Receipt_header.put("GlBatch", "");
				add_Receipt_header.put("AddUser", Strusername);
				add_Receipt_header.put("AddMach", macAddress);
				add_Receipt_header.put("AddDate", "");
				add_Receipt_header.put("CurRate", "1.000000");
				add_Receipt_header.put("customer_name", "");
				add_Receipt_header.put("payTypeDes", "");
				add_Receipt_header.put("CACHAcNo", "");
				add_Receipt_header.put("CACHAcBank", "");
				add_Receipt_header.put("CusBankCode", "");
				add_Receipt_header.put("CusBankName", "");
				add_Receipt_header.put("ActiveState", "1");
				add_Receipt_header.put("SyncState", "0");
				add_Receipt_header.put("AllocatedOriAmount", "0.00");
				add_Receipt_header.put("AllocatedAmount", "0.00");
				mydb.insert(FPRECHED_TABLE, null, add_Receipt_header);
				mydb.close();
			}
		}
	}

	private void getCurrentRefNumber() {
		// TODO Auto-generated method stub
		SO_Ref_Number = TransTypePrefix + Strlrepprefix + "/" + YearMonthStr
				+ "/" + currentSerialKey;
		etbbmsoreferenceno.setText(SO_Ref_Number);
		String[] separated = getAddDateTimeStringM().toString().split(" ");
		String StrTxnDate = separated[0]; // this will contain Date Part
		etbbmsodate.setText(getDeviceTaxnDate().toString());
		etbbmsocurrencyno.setText(CurrencyCode);
		Log.v(TAG, "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
		Log.v(TAG, "Current Ref Number*********24052014 :" + SO_Ref_Number);
	}

	private void getDefCurrencyCode() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curCurrency = null;
		try {
			String querySelectCurrency = "SELECT CurCode,CurDesc FROM fCurrency";
			curCurrency = mydb.rawQuery(querySelectCurrency, null);

		} catch (Exception e) {
		}
		if (curCurrency != null) {
			if (curCurrency.getCount() > 0) {
				while (curCurrency.moveToNext()) {
					String CurrencyCodeStr = curCurrency.getString(0);
					String CurrencyDes = curCurrency.getString(1);
					if (CurrencyDes.equals("Base Currancy")) {
						CurrencyCode = CurrencyCodeStr;
						ExchangeRate = "1.00";
					}
					if (CurrencyCodeStr.equals(CurrencyDes)) {
						ExchangeRate = "1.00";
					}
				}
			}
		}
	}

	// get year month strings
	private void getCurrentYearMonth() {
		// TODO Auto-generated method stub
		YearMonthStr = getRefYearMonth().toString();
	}

	// Get the current Company settings From DB
	private void getCompanySettings() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curgetcompanysettings = null;
		Cursor curgetcompanysettingsw = null;
		Cursor curgetcCharVal = null;
		String querygetcomsetings, querygetcomsetingsw;
		String querygetcCharVal;

		try {
			querygetcCharVal = "SELECT cSettingsCode,cCharVal,cCompanyCode FROM fCompanySetting Where cSettingsCode  = 'RCPDA'";
			curgetcCharVal = mydb.rawQuery(querygetcCharVal, null);
		} catch (Exception e) {
		}
		if (curgetcCharVal != null) {
			if (curgetcCharVal.getCount() > 0) {
				while (curgetcCharVal.moveToNext()) {
					String cCharVal = curgetcCharVal.getString(1);
					TransTypePrefix = cCharVal;
				}
			} else {
				TransTypePrefix = "R";
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_BBM_InvoiceSalesReceipt.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("INVALID SETTINGS CODE");
				// Setting Dialog Message
				alertDialog.setMessage("cSettingsCode Not Found..");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;

			}
		}
		Log.e("*****", "YEAR|" + getRefYearFull().toString() + "|");
		Log.e("*****", "USER|" + Strusername + "|");

		String currentMonth = getRefMonth().toString();
		int currentMonthVal = Integer.parseInt(currentMonth);
		if (currentMonthVal >= 10) {
			currentMonth = getRefMonth().toString();
		} else {
			currentMonth = getRefMonth().toString().replace("0", "");
		}
		Log.e("*****", "currentMonth|" + currentMonth + "|");

		try {
			querygetcomsetingsw = "SELECT FS.cSettingsCode,FS.cCharVal,FS.cCompanyCode,FB.cSettingsCodefb,FB.nYearb,FB.nMonthb,FB.nNumValfb,FB.BranchCode,FB.branch_id FROM fCompanySetting FS,FCompanyBranch FB WHERE FS.cSettingsCode = FB.cSettingsCodefb AND FS.cSettingsCode  = 'RCPDA'";
			curgetcompanysettingsw = mydb.rawQuery(querygetcomsetingsw, null);
		} catch (Exception e) {
		}
		if (curgetcompanysettingsw != null) {
			if (curgetcompanysettingsw.getCount() > 0) {
				while (curgetcompanysettingsw.moveToNext()) {
					String branch_id = curgetcompanysettingsw.getString(8);
				}
			}
		}

		try {
			querygetcomsetings = "SELECT FS.cSettingsCode,FS.cCharVal,FS.cCompanyCode,FB.cSettingsCodefb,FB.nYearb,FB.nMonthb,FB.nNumValfb,FB.BranchCode,FB.branch_id FROM fCompanySetting FS,FCompanyBranch FB WHERE FS.cSettingsCode = FB.cSettingsCodefb AND FS.cSettingsCode  = 'RCPDA' AND FB.BranchCode ='"
					+ Strusername.toUpperCase().trim()
					+ "' AND FB.nMonthb = '"
					+ currentMonth
					+ "' AND FB.nYearb ='"
					+ getRefYearFull().toString() + "'";
			curgetcompanysettings = mydb.rawQuery(querygetcomsetings, null);
		} catch (Exception e) {
		}
		if (curgetcompanysettings != null) {
			if (curgetcompanysettings.getCount() > 0) {
				while (curgetcompanysettings.moveToNext()) {
					String cSettingsCode = curgetcompanysettings.getString(0);
					String cCharVal = curgetcompanysettings.getString(1);
					currentRefNumber = curgetcompanysettings.getString(6);
					String cCompanyCode = curgetcompanysettings.getString(2);
					Log.e("*****", "cSettingsCode:" + cCharVal);
					Log.e("*****", "currentRefNumber:" + currentRefNumber);
					// ****Generate Reference Number /0001,0033****
					TransTypePrefix = cCharVal;
					if (currentRefNumber.length() == 1) {
						currentSerialKey = "00" + currentRefNumber;
					} else if (currentRefNumber.length() == 2) {
						currentSerialKey = "0" + currentRefNumber;
					} else {
						currentSerialKey = currentRefNumber;
					}

				}
			} else {
				currentRefNumber = "1";
				if (currentRefNumber.length() == 1) {
					currentSerialKey = "00" + currentRefNumber;
				} else if (currentRefNumber.length() == 2) {
					currentSerialKey = "0" + currentRefNumber;
				} else {
					currentSerialKey = currentRefNumber;
				}

				ContentValues contentFcomBranchMain = new ContentValues();
				contentFcomBranchMain.put("cSettingsCodefb", "RCPDA");
				contentFcomBranchMain.put("BranchCode", Strusername);
				contentFcomBranchMain.put("nNumValfb", currentRefNumber);
				contentFcomBranchMain.put("RecordId", "1");
				contentFcomBranchMain.put("nMonthb", currentMonth);
				contentFcomBranchMain
						.put("nYearb", getRefYearFull().toString());
				mydb.insert(FCOMPANYBRANCH_TABLE, null, contentFcomBranchMain);

			}
		}
		mydb.close();
	}

	// Get the current Users From DB
	private void getCurrentUser() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		String querygetuser;
		Cursor curgetuser = null;
		try {
			querygetuser = "SELECT * from usersettings";
			curgetuser = mydb.rawQuery(querygetuser, null);
		} catch (Exception e) {

		}

		if (curgetuser != null) {
			if (curgetuser.getCount() > 0) {
				while (curgetuser.moveToNext()) {
					Strusername = curgetuser.getString(1);
					Strlrepprefix = curgetuser.getString(2);
					if (Strlrepprefix != null) {
						Strlrepprefix = curgetuser.getString(2);
					} else {
						Strlrepprefix = "A";
					}
				}
			}
		}
	}

	private void getLoadCashBank() {
		// TODO Auto-generated method stub
		ListView InvoicesList = (ListView) findViewById(R.id.listviewcashbanks);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "colinvoice_1", "colinvoice_2" };
		int[] totrdes = new int[] { R.id.invbankdetails,
				R.id.invbankdetailsummary };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowtypedes = null;

		try {
			String queryListInv = "SELECT AccCode, AccDesc FROM Fglfacc WHERE AccCat ='4' OR AccCat = '2' AND CurCode = 'MVR'";
			allrowtypedes = mydb.rawQuery(queryListInv, null);
		} catch (Exception e) {
		}
		if (allrowtypedes != null) {
			if (allrowtypedes.getCount() > 0) {
				while (allrowtypedes.moveToNext()) {
					String AccCode = allrowtypedes.getString(0);
					String AccDesc = allrowtypedes.getString(1);

					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("colinvoice_1", AccCode + ":" + AccDesc);
					maptrdes.put("colinvoice_2", AccCode + "=" + AccDesc);

					fillMapstrdes.add(maptrdes);
				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_bbm_cash_banks_list_raw,
						fromtrdes, totrdes);
				InvoicesList.setAdapter(adaptertrdes);
			}
		}
		allrowtypedes.close();
		mydb.close();

	}

	/*************** Loading Cheque Present Bank **************/
	private void getLoadChqPresentBank() {
		// TODO Auto-generated method stub
		ListView InvoicesList = (ListView) findViewById(R.id.listviewchequebanks);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "colinvoice_1", "colinvoice_2" };
		int[] totrdes = new int[] { R.id.invbankdetails,
				R.id.invbankdetailsummary };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowtypedes = null;

		try {
			String queryListInv = "SELECT AccCode, AccDesc FROM Fglfacc WHERE AccCat ='4' OR AccCat = '2' AND CurCode = 'MVR'";
			allrowtypedes = mydb.rawQuery(queryListInv, null);
		} catch (Exception e) {
		}
		if (allrowtypedes != null) {
			if (allrowtypedes.getCount() > 0) {
				while (allrowtypedes.moveToNext()) {
					String AccCode = allrowtypedes.getString(0);
					String AccDesc = allrowtypedes.getString(1);

					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("colinvoice_1", AccCode + ":" + AccDesc);
					maptrdes.put("colinvoice_2", AccCode + "=" + AccDesc);

					fillMapstrdes.add(maptrdes);
				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_bbm_cheque_banks_list_raw,
						fromtrdes, totrdes);
				InvoicesList.setAdapter(adaptertrdes);
			}
		}
		allrowtypedes.close();
		mydb.close();

	}

	/*************** Loading Banks List **************/
	private void getLoadBanks() {
		// TODO Auto-generated method stub
		ListView InvoicesList = (ListView) findViewById(R.id.listviewbanks);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "colinvoice_1", "colinvoice_2" };
		int[] totrdes = new int[] { R.id.invbankdetails,
				R.id.invbankdetailsummary };
		// invbankdetails /invbankdetailsummary
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowtypedes = null;

		try {
			String queryListInv = "SELECT bankcode, bankname FROM fbank";
			allrowtypedes = mydb.rawQuery(queryListInv, null);
		} catch (Exception e) {
		}
		if (allrowtypedes != null) {
			if (allrowtypedes.getCount() > 0) {
				while (allrowtypedes.moveToNext()) {
					String BankCode = allrowtypedes.getString(0);
					String BankName = allrowtypedes.getString(1);

					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("colinvoice_1", BankCode + BankName);
					maptrdes.put("colinvoice_2", BankCode + BankName);

					fillMapstrdes.add(maptrdes);
				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_bbm_banks_list_raw,
						fromtrdes, totrdes);
				InvoicesList.setAdapter(adaptertrdes);
			}
		}
		allrowtypedes.close();
		mydb.close();
	}

	private void displayDefaultInfo() {
		// TODO Auto-generated method stub
		buttonSelectPayType.setText("CA");
		etbbmsoPayTypeDes.setText("CASH");
	}

	/************* Display Customer Details *************/
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void getLoadCustommers() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "*******populateCustomerDetailsList*******");
		Cursor cursor = dbHelperCustomer.fetchAllCustommers();
		// The desired columns to be bound
		String[] columns = new String[] { DM_BBM_List_Adapters.KEY_CUSCODE,
				DM_BBM_List_Adapters.KEY_CUSNAME };
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
		// the XML defined views which the data will be bound to
		int[] to = new int[] { R.id.invoicecustommer, R.id.invcustomername };

		// create the adapter using the cursor pointing to the desired data
		// as well as the layout information
		dataAdapterCusomer = new SimpleCursorAdapter(this,
				R.layout.dm_bbm_customer_list_raw, cursor, columns, to, 0);

		ListView listView = (ListView) findViewById(R.id.listviewcutommer);
		// Assign adapter to ListView
		listView.setAdapter(dataAdapterCusomer);

		myFilterCustomer.addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable s) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				dataAdapterCusomer.getFilter().filter(s.toString());
			}
		});

		dataAdapterCusomer.setFilterQueryProvider(new FilterQueryProvider() {
			public Cursor runQuery(CharSequence constraint) {
				return dbHelperCustomer.fetchAllCustommersByName(constraint
						.toString());
			}
		});
	}

	public void AddCustomerDetails(View view) {
		String ReceivedAmount = etreceiptamount.getText().toString().trim();
		String BalanceAmount = etbalamount.getText().toString().trim();

		/*****
		 * Reset values on customer selection only if the alance Amount not
		 * Eqals to Originally added allocated amount
		 *****/
		if (ReceivedAmount.equals(BalanceAmount)) {
			Log.v(TAG, "NEW Customer..");
		} else {
			resetAllRecords();
		}

		dminvoiceselectchequebank.setVisibility(view.GONE);
		dminvoiceselectbank.setVisibility(view.GONE);
		dminvoiceselectcus.setVisibility(view.GONE);
		dminvoiceheadersection.setVisibility(view.VISIBLE);
		Button des = (Button) view;
		String SetTransactionDesc = des.getText().toString();
		CustomerCodeInv = SetTransactionDesc.trim();
		viewDebtorDetails();
		DisplayOutStandingReceipts();
	}

	public void AddReceiptsDetails(View view) {
		PreviewReceipt = 202;
		dminvoiceselectcus.setVisibility(view.GONE);
		dminvoiceheadersection.setVisibility(view.VISIBLE);
		dminvoiceselectbank.setVisibility(view.GONE);
		dminvoiceselectcashbank.setVisibility(view.GONE);
		dminvoiceselectchequebank.setVisibility(view.GONE);
		dminvoiceselectinvoices.setVisibility(view.GONE);
		btndeletetransaction.setEnabled(true);
		btnprinttransaction.setEnabled(true);
		btnsavetransaction.setEnabled(false);
		Button des = (Button) view;
		String SetTransactionDesc = des.getText().toString();
		receiptRefNoSelected = SetTransactionDesc.trim();
		viewReceiptHeader();

	}

	private void viewReceiptHeader() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor checkReceiptHeader = null;
		try {
			String checkReceipthed = "SELECT * FROM FPRecHed WHERE RefNo = '"
					+ receiptRefNoSelected + "'";
			checkReceiptHeader = mydb.rawQuery(checkReceipthed, null);

		} catch (Exception e) {
		}

		if (checkReceiptHeader != null) {
			if (checkReceiptHeader.getCount() > 0) {
				while (checkReceiptHeader.moveToNext()) {
					String RefNo = checkReceiptHeader.getString(1);
					String TxnDate = checkReceiptHeader.getString(8);
					String CurCode = checkReceiptHeader.getString(9);
					String ManuRef = checkReceiptHeader.getString(2);
					CustomerCodeInv = checkReceiptHeader.getString(11);
					String customer_name = checkReceiptHeader.getString(34);
					String PayType = checkReceiptHeader.getString(21);
					String payTypeDes = checkReceiptHeader.getString(35);
					String Chqno = checkReceiptHeader.getString(6);
					String ChqDate = checkReceiptHeader.getString(7);
					String CusBankCode = checkReceiptHeader.getString(38);
					String CusBankName = checkReceiptHeader.getString(39);
					String CACHAcNo = checkReceiptHeader.getString(36);
					String CACHAcBank = checkReceiptHeader.getString(37);
					String Remarks = checkReceiptHeader.getString(24);
					String AllocatedOriAmount = checkReceiptHeader
							.getString(42);
					String AllocatedBalAmount = checkReceiptHeader
							.getString(43);
					String BankRate = checkReceiptHeader.getString(15);
					etbbmsoreferenceno.setText(RefNo);
					etbbmsodate.setText(TxnDate);
					etbbmsocurrencyno.setText(CurCode);
					etbbmsomanualno.setText(ManuRef);
					buttonSelectCustomer.setText(CustomerCodeInv);
					etbbmsoCustomer.setText(customer_name);
					buttonSelectPayType.setText(PayType);
					etbbmsoPayTypeDes.setText(payTypeDes);
					if (PayType.trim().equals("CA")) {
						etcachebankacc.setText(CACHAcNo);
						etcachebankaccdetail.setText(CACHAcBank);
					} else {
						chequedetailspanel.setVisibility(LinearLayout.VISIBLE);
						etbbmchequeno.setText(Chqno);
						btndatebepresent.setText(ChqDate);
						btnbbmcusbank.setText(CusBankCode);
						etbbmcusbank.setText(CusBankName);
						buttonbbmchqpbankcode.setText(CACHAcNo);
						etbbmchqpbankdescription.setText(CACHAcBank);
					}

					etreceiptrate.setText(BankRate);
					etreceiptamount.setText(AllocatedBalAmount);
					etbbmreceiptremark.setText(Remarks);

				}
			}
		}

		DisplayReceiptPreviewDetails();
	}

	private void resetAllRecords() {
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// TODO Auto-generated method stub
		String currentRefNo = etbbmsoreferenceno.getText().toString();
		Cursor checkReceiptState = null;
		try {
			String queryChkSalesOrder = "SELECT ActiveState FROM FPRecHed WHERE RefNo = '"
					+ currentRefNo + "'";
			checkReceiptState = mydb.rawQuery(queryChkSalesOrder, null);

		} catch (Exception e) {
		}
		if (checkReceiptState != null) {
			if (checkReceiptState.getCount() > 0) {
				while (checkReceiptState.moveToNext()) {
					String CurrentState = checkReceiptState.getString(0);
					if (CurrentState.equals("1")) {
						AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
								DM_BBM_InvoiceSalesReceipt.this);
						alertDialogBuilder.setTitle("RESET CURRENT RECEIPT");
						alertDialogBuilder
								.setMessage("Undo Current Receipt Details");
						// set positive button: Yes message
						alertDialogBuilder.setPositiveButton("Yes",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										resetCode = 100;
										undoActionActivate();
									}
								});
						// set negative button: No message
						alertDialogBuilder.setNegativeButton("No",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {

										dialog.cancel();
									}
								});

						AlertDialog alertDialog = alertDialogBuilder.create();
						// show alert
						alertDialog.show();
					}
				}
			}
		}
	}

	public void AddBanksDetails(View view) {
		dminvoiceselectchequebank.setVisibility(view.GONE);
		dminvoiceselectbank.setVisibility(view.GONE);
		dminvoiceselectcus.setVisibility(view.GONE);
		dminvoiceheadersection.setVisibility(view.VISIBLE);
		Button des = (Button) view;
		String bankDescription = des.getText().toString();
		String[] separated = bankDescription.split("-");
		String BankCode = separated[0];
		String BankCodeDes = separated[1];

		btnbbmcusbank.setText(BankCode.trim());
		etbbmcusbank.setText(BankCodeDes.trim());
	}

	public void AddChequeBanksDetails(View view) {
		dminvoiceselectchequebank.setVisibility(view.GONE);
		dminvoiceselectbank.setVisibility(view.GONE);
		dminvoiceselectcus.setVisibility(view.GONE);
		dminvoiceheadersection.setVisibility(view.VISIBLE);
		Button des = (Button) view;
		String chqbankDescription = des.getText().toString();
		String[] separated = chqbankDescription.split("=");
		String chqBankCode = separated[0];
		String chqBankCodeDes = separated[1];

		buttonbbmchqpbankcode.setText(chqBankCode);
		etbbmchqpbankdescription.setText(chqBankCodeDes);
	}

	public void AddCashBanksDetails(View view) {
		dminvoiceselectcashbank.setVisibility(view.GONE);
		dminvoiceselectchequebank.setVisibility(view.GONE);
		dminvoiceselectbank.setVisibility(view.GONE);
		dminvoiceselectcus.setVisibility(view.GONE);
		dminvoiceheadersection.setVisibility(view.VISIBLE);
		Button des = (Button) view;
		String chqbankDescription = des.getText().toString();
		String[] separated = chqbankDescription.split("=");
		String chqBankCode = separated[0];
		String chqBankCodeDes = separated[1];

		etcachebankacc.setText(chqBankCode);
		etcachebankaccdetail.setText(chqBankCodeDes);
	}

	private void viewDebtorDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor debTaxDet = null;
		Cursor allrowtypedes = null;
		try {
			String querySelectDebtorTax = "SELECT ft.DebCode,ft.TaxRegNo FROM fDebTax ft Where ft.DebCode = '"
					+ CustomerCodeInv.trim() + "'";
			debTaxDet = mydb.rawQuery(querySelectDebtorTax, null);

		} catch (Exception e) {
		}
		if (debTaxDet != null) {
			if (debTaxDet.getCount() > 0) {
				while (debTaxDet.moveToNext()) {
					CustomerTaxRegNo = debTaxDet.getString(1);
				}
			}
		}

		try {
			String querySelectDebtor = "SELECT fd.DebCode,fd.DebName,fd.TaxReg,fd.DebAdd1,fd.DebAdd2,fd.DebAdd3,fd.DebTele FROM fDebtor fd Where fd.DebCode = '"
					+ CustomerCodeInv.trim() + "'";
			allrowtypedes = mydb.rawQuery(querySelectDebtor, null);

		} catch (Exception e) {
		}

		if (allrowtypedes != null) {
			if (allrowtypedes.getCount() > 0) {
				while (allrowtypedes.moveToNext()) {
					CustomerCodeInv = allrowtypedes.getString(0);
					String customername = allrowtypedes.getString(1);
					buttonSelectCustomer.setText(CustomerCodeInv);
					etbbmsoCustomer.setText(customername);
				}
			}
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DATE_DIALOG_ID_FROM:
			// create a new DatePickerDialog with values you want to show
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);

		}
		return InvoiceHeaderAlert;
	}

	// Register DatePickerDialog listener
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		// the callback received when the user "sets" the Date in the
		// DatePickerDialog
		public void onDateSet(DatePicker view, int yearSelected,
				int monthOfYear, int dayOfMonth) {
			mYear = yearSelected;
			mMonth = monthOfYear + 1;
			mDay = dayOfMonth;
			String mMonthStr = Integer.toString(mMonth);
			String mDayStr = Integer.toString(mDay);
			if (mMonthStr.length() == 1) {
				mMonthStr = "0" + mMonthStr;
			}
			if (mDayStr.length() == 1) {
				mDayStr = "0" + mDayStr;
			}
			btndatebepresent.setText(mDayStr + "/" + mMonthStr + "/" + mYear);
			mMonth = mMonth - 1;
		}
	};

	private String getRefYearMonth() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyMM");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	private String getRefYear() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat Year = new SimpleDateFormat("yy");
		String currentYear = Year.format(cad.getTime());
		return currentYear;
	}

	private String getRefYearFull() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat Year = new SimpleDateFormat("yyyy");
		String currentYear = Year.format(cad.getTime());
		return currentYear;
	}

	private String getRefMonth() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat Month = new SimpleDateFormat("MM");
		String currentMonth = Month.format(cad.getTime());
		return currentMonth;
	}

	private String getAddDateTimeStringM() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	private String getAddTaxnDate() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("dd-MM-yyyy");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	private String getDeviceTaxnDate() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("dd/MM/yyyy");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	@Override
	public boolean onNavigationItemSelected(int arg0, long arg1) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main_actions, menu);
		return true;
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_search:
			// search action
			return true;
		case R.id.action_location_found:
			// location found
			BackAction();
			return true;
		case R.id.action_refresh:
			// refresh
			return true;
		case R.id.action_help:
			// help action
			return true;
		case R.id.action_check_updates:
			// check for updates action
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void BackAction() {
		// TODO Auto-generated method stub
		Intent i = new Intent(DM_BBM_InvoiceSalesReceipt.this,
				DM_BBM_InvoiceMenu.class);
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(i);
		finish();
		return;
	}

	public void DisplayReceiptSumDetails(View view) {

		String PendingBal = etbalamount.getText().toString();
		BigDecimal PendingBalValue = new BigDecimal(PendingBal.replaceAll(
				"[,]", ""));
		int resCom;
		resCom = PendingBalValue.compareTo(defaultAllocatedAmount);

		if (resCom == -1) {
			Log.e("TAG", "VALUE 111:" + PendingBal);
			AlertDialog.Builder builderSingle = new AlertDialog.Builder(
					DM_BBM_InvoiceSalesReceipt.this);
			builderSingle.setTitle("Invalid Allocation");
			builderSingle
					.setMessage("Do You Want To Reallocate Receipt Amounts ?");
			builderSingle.setNegativeButton("No",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							String AdditionalAmount = etbalamount.getText()
									.toString().replaceAll("-", "");
							String AdjustValue = etreceiptamount.getText()
									.toString().replaceAll("-", "");
							BigDecimal AdditionalValAmount = new BigDecimal(
									AdditionalAmount.replaceAll("[,]", ""));
							BigDecimal AdjustValAmount = new BigDecimal(
									AdjustValue.replaceAll("[,]", ""));
							BigDecimal PrintNewValue = AdditionalValAmount
									.add(AdjustValAmount);
							etreceiptamount.setText("" + PrintNewValue);
							dialog.dismiss();
						}
					});

			builderSingle.setPositiveButton("Yes",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							undoActionActivate();
							dialog.dismiss();
						}
					});

			AlertDialog alertDialog = builderSingle.create();
			// show alert
			alertDialog.show();

		} else {
			updateReceiptHeaderDetails();

			if (buttonSelectCustomer.getText().toString().trim().length() != 0) {
				if (etbalamount.getText().toString().trim().length() != 0) {

					BigDecimal currentBalace = new BigDecimal(etreceiptamount
							.getText().toString().trim().replaceAll("[,]", ""));

					int res;
					res = currentBalace.compareTo(defaultAllocatedAmount); // compare
																			// bg1
																			// with
																			// bg2
					Log.v(TAG, "COMPAIR : " + res);
					if (res == 0) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_BBM_InvoiceSalesReceipt.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("INVALID ALLOCATED AMOUNT");
						// Setting Dialog Message
						alertDialog.setMessage("Current Allocating Amount("
								+ defaultAllocatedAmount
								+ ")  Please Enter Receipt Allocating Amount");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					} else if (ReceiptCount == 0) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_BBM_InvoiceSalesReceipt.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("EMPTY RECEIPTS");
						// Setting Dialog Message
						alertDialog
								.setMessage("Receipts Not Found For Selected Customer..");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					}

					else {

						Button des = (Button) view;
						String MainReceiptCode = des.getText().toString();
						String MainRefNo = etbbmsoreferenceno.getText()
								.toString().trim();

						Intent myIntent = new Intent(view.getContext(),
								DM_BBM_Bal_Receipt_Amt_Details.class);
						myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
								| Intent.FLAG_ACTIVITY_NEW_TASK);
						myIntent.putExtra("TAGID", MainReceiptCode);
						myIntent.putExtra("TAGIDREF", MainRefNo);
						startActivityForResult(myIntent, 0);
						finish();
						return;
					}
				}

				else {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_BBM_InvoiceSalesReceipt.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("INVALID AMOUNT");
					// Setting Dialog Message
					alertDialog
							.setMessage("Please Enter Receipt Allocating Amount");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;

				}

			} else {
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_BBM_InvoiceSalesReceipt.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("SELECT CUSTOMER");
				// Setting Dialog Message
				alertDialog.setMessage("Select Customer From The List");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;

			}
		}
	}

	private void updateReceiptHeaderDetails() {
		// TODO Auto-generated method stub
		Log.v(TAG, "***** updateReceiptHeaderDetails *****");
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		try {
			ContentValues add_Receipt_Hed_Update = new ContentValues();
			add_Receipt_Hed_Update.put("RefNo", etbbmsoreferenceno.getText()
					.toString());
			add_Receipt_Hed_Update.put("TxnDate", getDeviceTaxnDate()
					.toString());
			add_Receipt_Hed_Update.put("CurCode", etbbmsocurrencyno.getText()
					.toString());
			add_Receipt_Hed_Update.put("BankCur", etbbmsocurrencyno.getText()
					.toString());
			add_Receipt_Hed_Update.put("ManuRef", etbbmsomanualno.getText()
					.toString());
			add_Receipt_Hed_Update.put("DebCode", buttonSelectCustomer
					.getText().toString());
			add_Receipt_Hed_Update.put("customer_name", etbbmsoCustomer
					.getText().toString());
			add_Receipt_Hed_Update.put("PayType", buttonSelectPayType.getText()
					.toString());
			add_Receipt_Hed_Update.put("payTypeDes", etbbmsoPayTypeDes
					.getText().toString());
			add_Receipt_Hed_Update.put("Chqno", etbbmchequeno.getText()
					.toString());
			add_Receipt_Hed_Update.put("ChqDate", btndatebepresent.getText()
					.toString());
			add_Receipt_Hed_Update.put("CusBankCode", btnbbmcusbank.getText()
					.toString());
			add_Receipt_Hed_Update.put("CusBankName", etbbmcusbank.getText()
					.toString());
			String CurrentPayOption = buttonSelectPayType.getText().toString()
					.trim();
			if (CurrentPayOption.equals("CH")) {
				Log.v(TAG, "******PayType SAVE CH: "
						+ buttonbbmchqpbankcode.getText().toString());
				add_Receipt_Hed_Update.put("DbAcc", buttonbbmchqpbankcode
						.getText().toString());
				add_Receipt_Hed_Update.put("CACHAcNo", buttonbbmchqpbankcode
						.getText().toString());
				add_Receipt_Hed_Update.put("CACHAcBank",
						etbbmchqpbankdescription.getText().toString());
			} else if (CurrentPayOption.equals("CA")) {
				Log.v(TAG, "******PayType SAVE CA: "
						+ etcachebankacc.getText().toString());
				add_Receipt_Hed_Update.put("DbAcc", etcachebankacc.getText()
						.toString());
				add_Receipt_Hed_Update.put("CACHAcNo", etcachebankacc.getText()
						.toString());
				add_Receipt_Hed_Update.put("CACHAcBank", etcachebankaccdetail
						.getText().toString());
			}
			add_Receipt_Hed_Update.put("BankRate", etreceiptrate.getText()
					.toString());
			add_Receipt_Hed_Update.put("Remarks", etbbmreceiptremark.getText()
					.toString());
			add_Receipt_Hed_Update.put("AddDate", getAddDateTimeStringM()
					.toString());

			BigDecimal AllocMainVal = new BigDecimal(etreceiptamount.getText()
					.toString().replaceAll("[,]", ""));
			AllocMainVal = AllocMainVal.setScale(2, BigDecimal.ROUND_HALF_DOWN);

			add_Receipt_Hed_Update.put("AllocatedOriAmount", "" + AllocMainVal);
			add_Receipt_Hed_Update.put("AllocatedAmount", etbalamount.getText()
					.toString());
			mydb.update(FPRECHED_TABLE, add_Receipt_Hed_Update, "RefNo = '"
					+ SO_Ref_Number + "'", null);

		} catch (Exception e) {
			Log.v(TAG, "Exception :" + e);
		}

	}

	// ***********************************************************************************
	private TextWatcher calculateBalanceAmountReceived = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			Log.v(TAG, "afterTextChanged 1");

			if (etreceiptamount.length() != 0) {
				if (etreceiptallocamount.length() != 0) {
					String OriginalAllocatedAmt = etreceiptamount.getText()
							.toString();
					String ReceiptsAllocatedAmt = etreceiptallocamount
							.getText().toString();
					try {
						RecOriAllocatedAmount = new BigDecimal(
								OriginalAllocatedAmt.replaceAll("[,]", ""));
						RecAllocatedAmount = new BigDecimal(
								ReceiptsAllocatedAmt.replaceAll("[,]", ""));

						RecBalanceAmount = RecOriAllocatedAmount
								.subtract(RecAllocatedAmount);
						RecBalanceAmount = RecBalanceAmount.setScale(2,
								BigDecimal.ROUND_HALF_DOWN);

					} catch (Exception e) {
						Log.v("TAG", "Invalid Calculation");
					}
					etbalamount.setText("" + RecBalanceAmount);

					Log.v(TAG, "afterTextChanged 1" + "" + RecBalanceAmount);
					if (resetActive == 202) {
						resetActive = 0;
						etreceiptallocamount.setText("0.00");
						etreceiptamount.setText("0.00");
						etbalamount.setText("0.00");
						RecOriAllocatedAmount = new BigDecimal("0.00");
						RecAllocatedAmount = new BigDecimal("0.00");
						RecBalanceAmount = new BigDecimal("0.00");
					}

				}
			} else {
				etreceiptamount.setText("0.00");
			}

		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			Log.v(TAG, "beforeTextChanged");
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			Log.v(TAG, "onTextChanged");
		}

	};

	private TextWatcher calculateReceiptAmountReceived = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			Log.v(TAG, "afterTextChanged 1");
			if (etreceiptamount.length() != 0) {
				if (etreceiptallocamount.length() != 0) {
					String OriginalAllocatedAmt = etreceiptamount.getText()
							.toString();
					String ReceiptsAllocatedAmt = etreceiptallocamount
							.getText().toString();

					RecOriAllocatedAmount = new BigDecimal(
							OriginalAllocatedAmt.replaceAll("[,]", ""));
					RecAllocatedAmount = new BigDecimal(
							ReceiptsAllocatedAmt.replaceAll("[,]", ""));

					RecBalanceAmount = RecOriAllocatedAmount
							.subtract(RecAllocatedAmount);
					RecBalanceAmount = RecBalanceAmount.setScale(2,
							BigDecimal.ROUND_HALF_DOWN);
					etbalamount.setText("" + RecBalanceAmount);

					Log.v(TAG, "afterTextChanged 1" + "" + RecBalanceAmount);
					if (resetActive == 202) {
						resetActive = 0;
						etreceiptallocamount.setText("0.00");
						etreceiptamount.setText("0.00");
						etbalamount.setText("0.00");
						RecOriAllocatedAmount = new BigDecimal("0.00");
						RecAllocatedAmount = new BigDecimal("0.00");
						RecBalanceAmount = new BigDecimal("0.00");
					}

				}
			} else {
				etreceiptamount.setText("0.00");
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			Log.v(TAG, "beforeTextChanged");
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			Log.v(TAG, "onTextChanged");
		}

	};

	private void updateFCompanyBranch() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		String currentMonth = getRefMonth().toString();
		int currentMonthVal = Integer.parseInt(currentMonth);
		if (currentMonthVal >= 10) {
			currentMonth = getRefMonth().toString();
		} else {
			currentMonth = getRefMonth().toString().replace("0", "");
		}
		Cursor curgetcompanysettings = null;
		String querygetcomsetings;
		try {

			querygetcomsetings = "SELECT * FROM FCompanyBranch WHERE cSettingsCodefb = 'RCPDA' AND BranchCode ='"
					+ Strusername
					+ "'  AND nMonthb = '"
					+ currentMonth
					+ "' AND nYearb ='" + getRefYearFull().toString() + "'";
			curgetcompanysettings = mydb.rawQuery(querygetcomsetings, null);
		} catch (Exception e) {
		}
		if (curgetcompanysettings != null) {
			if (curgetcompanysettings.getCount() > 0) {
				while (curgetcompanysettings.moveToNext()) {
					String cSettingsCodefb = curgetcompanysettings.getString(1);// cSettingsCodefb
					String nNumValfb = curgetcompanysettings.getString(3);// nNumValfb

					int NewnNumValue = Integer.parseInt(nNumValfb);
					NewnNumValue = NewnNumValue + 1;
					ContentValues updateFComBranch = new ContentValues();
					updateFComBranch.put("nNumValfb", "" + NewnNumValue);
					mydb.update(FCOMPANYBRANCH_TABLE, updateFComBranch,
							"cSettingsCodefb = 'RCPDA'", null);

					currentRefNumber = "" + NewnNumValue;

					if (currentRefNumber.length() == 1) {
						currentSerialKey = "00" + currentRefNumber;
					} else if (currentRefNumber.length() == 2) {
						currentSerialKey = "0" + currentRefNumber;
					} else {
						currentSerialKey = currentRefNumber;
					}
					getCurrentRefNumber();
					addNewReceiptNumber();
				}
			} else {
				currentRefNumber = "1";
				ContentValues contentFcomBranchMain = new ContentValues();
				contentFcomBranchMain.put("cSettingsCodefb", "RCPDA");
				contentFcomBranchMain.put("BranchCode", Strusername);
				contentFcomBranchMain.put("nNumValfb", currentRefNumber);
				contentFcomBranchMain.put("RecordId", "1");
				contentFcomBranchMain.put("nMonthb", currentMonth);
				contentFcomBranchMain
						.put("nYearb", getRefYearFull().toString());
				mydb.insert(FCOMPANYBRANCH_TABLE, null, contentFcomBranchMain);

			}
		}
		mydb.close();
	}

	private void addNewReceiptNumber() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			ContentValues add_Receipt_header = new ContentValues();
			add_Receipt_header.put("RefNo", SO_Ref_Number);
			add_Receipt_header.put("ManuRef", "");
			add_Receipt_header.put("SaleRefNo", "");
			add_Receipt_header.put("RepCode", Strusername);
			add_Receipt_header.put("TxnType", "40");
			add_Receipt_header.put("Chqno", "");
			add_Receipt_header.put("ChqDate", "");
			add_Receipt_header.put("TxnDate", getDeviceTaxnDate().toString());
			add_Receipt_header.put("CurCode", CurrencyCode);
			add_Receipt_header.put("CurRate1", "0.000000");
			add_Receipt_header.put("DebCode", "");
			add_Receipt_header.put("TotalAmt", "");
			add_Receipt_header.put("BTotalAmt", "");
			add_Receipt_header.put("BankCur", "");
			add_Receipt_header.put("BankRate", "1.000000");
			add_Receipt_header.put("BankAmt", "");
			add_Receipt_header.put("BankCharge", "");
			add_Receipt_header.put("BBankChg", "");
			add_Receipt_header.put("GnLsCal", "Y");
			add_Receipt_header.put("DbAcc", "");
			add_Receipt_header.put("PayType", "");
			add_Receipt_header.put("PrtCopy", "1");
			add_Receipt_header.put("GlPost", "");
			add_Receipt_header.put("Remarks", "");
			add_Receipt_header.put("CardSlipNo", "");
			add_Receipt_header.put("ExpDate", "");
			add_Receipt_header.put("CrdTypCode", "");
			add_Receipt_header.put("CCBankAmt", "");
			add_Receipt_header.put("GlBatch", "");
			add_Receipt_header.put("AddUser", Strusername);
			add_Receipt_header.put("AddMach", macAddress);
			add_Receipt_header.put("AddDate", "");
			add_Receipt_header.put("CurRate", "1.000000");
			add_Receipt_header.put("customer_name", "");
			add_Receipt_header.put("payTypeDes", "");
			add_Receipt_header.put("CACHAcNo", "");
			add_Receipt_header.put("CACHAcBank", "");
			add_Receipt_header.put("CusBankCode", "");
			add_Receipt_header.put("CusBankName", "");
			add_Receipt_header.put("ActiveState", "1");
			add_Receipt_header.put("SyncState", "0");
			add_Receipt_header.put("AllocatedOriAmount", "0.00");
			add_Receipt_header.put("AllocatedAmount", "0.00");
			mydb.insert(FPRECHED_TABLE, null, add_Receipt_header);
		} catch (Exception e) {

		}
		mydb.close();
	}

	private void UpdateReceipt() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		String CurrentReceiptRef = etbbmsoreferenceno.getText().toString();
		Cursor checkReceiptDet = null;
		try {
			String querySelectDebtor = "SELECT * FROM FPRecDet WHERE RefNo = '"
					+ CurrentReceiptRef + "'";
			checkReceiptDet = mydb.rawQuery(querySelectDebtor, null);
		} catch (Exception e) {
		}
		if (checkReceiptDet != null) {
			if (checkReceiptDet.getCount() > 0) {
				while (checkReceiptDet.moveToNext()) {
					String receiptRef = checkReceiptDet.getString(2);
					String allocateValue = checkReceiptDet.getString(18);

					Cursor checkfddbnote = null;
					try {
						String querycheckfddbnote = "SELECT * FROM fddbnote WHERE RefNo = '"
								+ receiptRef + "'";
						checkfddbnote = mydb.rawQuery(querycheckfddbnote, null);
					} catch (Exception e) {
					}
					if (checkfddbnote != null) {
						if (checkfddbnote.getCount() > 0) {
							while (checkfddbnote.moveToNext()) {
								String currentTotBal = checkfddbnote
										.getString(9);
								BigDecimal currentTotBalValue = new BigDecimal(
										currentTotBal.replaceAll("[,]", ""));
								BigDecimal NewAllocation = new BigDecimal(
										allocateValue.replaceAll("[,]", ""));
								BigDecimal UpdateNewBalValue = currentTotBalValue
										.subtract(NewAllocation);

								ContentValues fddbnoteupdate = new ContentValues();
								fddbnoteupdate.put("Totbal", ""
										+ UpdateNewBalValue);
								mydb.update(FDDBNOTE_TABLE, fddbnoteupdate,
										"RefNo = '" + receiptRef + "'", null);
							}
						}
					}

				}
			}
		}
		mydb.close();
	}

	/******************* SAVE ACTION VALIDATOR ************************/
	protected void checkCustomer() {
		// TODO Auto-generated method stub
		if (buttonSelectCustomer.getText().toString().trim().length() == 0) {
			SaveAlertTitle = "Invalid Customer";
			SaveAlertDetailMessage = "Please Select Customer.";
			showAlert();
		} else {
			checkAllocatedBalAmount();
		}
	}

	protected void checkAllocatedBalAmount() {
		// TODO Auto-generated method stub
		BigDecimal BalanceAmount = new BigDecimal(etbalamount.getText()
				.toString().replaceAll("[,]", ""));
		int res;
		res = BalanceAmount.compareTo(defaultAllocatedAmount);
		if (res == 1) {
			SaveAlertTitle = "SAVE FAIL";
			SaveAlertDetailMessage = "Invalid Receipt Details, Save Failed. Balance Amount Should Be 0.00";
			showAlert();
		} else {
			checkCashCheckValidation();
		}
	}

	private void checkCashCheckValidation() {
		// TODO Auto-generated method stub
		String parentCashType = buttonSelectPayType.getText().toString().trim();
		if (parentCashType.equals("CA")) {
			receiptSaveValidate();
			// Remove Validation On 27/07/2014
			/*
			 * if (etcachebankacc.getText().toString().trim().length() == 0) {
			 * SaveAlertTitle = "INVALID BANK"; SaveAlertDetailMessage =
			 * "Please Enter Cash Bank Details."; showAlert(); } else {
			 * receiptSaveValidate(); }
			 */
		} else if (parentCashType.equals("CH")) {
			if (etbbmchequeno.getText().toString().trim().length() == 0) {
				SaveAlertTitle = "INVALID CHEQUE NO";
				SaveAlertDetailMessage = "Please Enter Cheque Number.";
				showAlert();
			} else if (btndatebepresent.getText().toString().trim().length() == 0) {
				SaveAlertTitle = "INVALID CHEQUE DATE";
				SaveAlertDetailMessage = "Please Enter Cheque Date.";
				showAlert();
			} else if (btnbbmcusbank.getText().toString().trim().length() == 0) {
				SaveAlertTitle = "INVALID BANK";
				SaveAlertDetailMessage = "Please Enter Customer Bank.";
				showAlert();
			}
			// Remove Validation On 27/07/2014
			/*
			 * else if (buttonbbmchqpbankcode.getText().toString().trim()
			 * .length() == 0) { SaveAlertTitle = "INVALID CHEQUE BANK";
			 * SaveAlertDetailMessage = "Please Enter Cheque Present Bank.";
			 * showAlert(); }
			 */

			else {
				receiptSaveValidate();
			}
		}

	}

	private void receiptSaveValidate() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		String CurrentReceiptRef = etbbmsoreferenceno.getText().toString();

		Cursor checkReceiptDet = null;

		try {
			String querySelectDebtor = "SELECT * FROM FPRecDet WHERE RefNo = '"
					+ CurrentReceiptRef + "'";
			checkReceiptDet = mydb.rawQuery(querySelectDebtor, null);
		} catch (Exception e) {
		}

		if (checkReceiptDet != null) {
			if (checkReceiptDet.getCount() > 0) {
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
						DM_BBM_InvoiceSalesReceipt.this);
				alertDialogBuilder.setTitle("SAVE RECEIPT");
				alertDialogBuilder.setMessage("Save Receipt Details");
				// set positive button: Yes message
				alertDialogBuilder.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								UpdateReceiptHeader();
								UpdateReceipt();
								updateFCompanyBranch();
								exitFromView();
								dialog.cancel();

							}

							private void exitFromView() {
								// TODO Auto-generated method
								// stub
								Intent i = new Intent(
										DM_BBM_InvoiceSalesReceipt.this,
										DM_BBM_InvoiceMenu.class);
								i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
										| Intent.FLAG_ACTIVITY_NEW_TASK);
								startActivity(i);
								finish();
								return;
							}

							private void UpdateReceiptHeader() {
								// TODO Auto-generated method
								// stub
								mydb = openOrCreateDatabase(DBNAME,
										Context.MODE_PRIVATE, null);
								try {
									ContentValues add_Receipt_Hed_Update = new ContentValues();
									add_Receipt_Hed_Update.put("ActiveState",
											"0");
									mydb.update(FPRECHED_TABLE,
											add_Receipt_Hed_Update,
											"ActiveState = '1'", null);
								} catch (Exception e) {

								}
							}
						});
				// set negative button: No message
				alertDialogBuilder.setNegativeButton("No",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// cancel the alert box and put
								// a Toast
								// to
								// the
								// user
								dialog.cancel();
							}
						});
				// set neutral button: Exit the app message
				alertDialogBuilder.setNeutralButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// exit the app and go to the
								// HOME
								dialog.cancel();
							}
						});

				AlertDialog alertDialog = alertDialogBuilder.create();
				// show alert
				alertDialog.show();
			} else {
				SaveAlertTitle = "SAVE FAIL";
				SaveAlertDetailMessage = "Invalid Receipt Details, Save Failed. Balance Amount Should Be 0.00";
				showAlert();
			}
		} else {
			SaveAlertTitle = "SAVE FAIL";
			SaveAlertDetailMessage = "Invalid Receipt Details, Save Failed. Balance Amount Should Be 0.00";
			showAlert();
		}
	}

	// Display Network connection Fail Alert
	public void showAlertDialog(Context context, String title, String message,
			Boolean status) {
		final AlertDialog alertDialog = new AlertDialog.Builder(context)
				.create();

		// Setting Dialog Title
		alertDialog.setTitle(title);

		// Setting Dialog Message
		alertDialog.setMessage(message);

		// Setting alert dialog icon
		alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// new DownloadAdministrative().execute();
				delPressed = 0;
				alertDialog.dismiss();
			}
		});

		// Showing Alert Message
		alertDialog.show();
	}

	private void showAlert() {
		// TODO Auto-generated method stub
		final AlertDialog alertDialog = new AlertDialog.Builder(
				DM_BBM_InvoiceSalesReceipt.this).create();
		// Setting Dialog Title
		alertDialog.setTitle(SaveAlertTitle);
		// Setting Dialog Message
		alertDialog.setMessage(SaveAlertDetailMessage);
		// Setting Icon to Dialog
		alertDialog.setIcon(R.drawable.warning);
		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				resetTitles();
				alertDialog.dismiss();
			}
		});
		// Showing Alert Message
		alertDialog.show();
		alertDialog.setCanceledOnTouchOutside(false);
		return;
	}

	protected void resetTitles() {
		// TODO Auto-generated method stub
		SaveAlertTitle = "";
		SaveAlertDetailMessage = "";
	}

}
